import { PrismaService } from 'nestjs-prisma';
import { GetSkit, GetSort } from '../utils/query';
import { PageDto } from '../dto/page.dto';
import { BadRequestException } from '@nestjs/common';

export class CrudService {
  model: string = '';
  constructor(
    readonly prisma: PrismaService,
    model: string,
  ) {
    this.model = model;
  }

  async queryPage(query: any, where: any, include?: any) {
    const list = this.prisma[this.model].findMany({
      where,
      ...GetSort(query),
      ...GetSkit(query),
      ...(include || {}),
    });
    const count = this.prisma[this.model].count({ where });

    try {
      const result = await this.prisma.$transaction([list, count]);
      return new PageDto(query, ...result);
    } catch (e) {
      throw new BadRequestException(e.message);
    }
  }

  remove(id: string) {
    return this.prisma[this.model].delete({ where: { id } });
  }

  findOne(id: string) {
    return this.prisma[this.model].findUnique({
      where: { id },
    });
  }

  findAll<T>(where?: T) {
    return this.prisma[this.model].findMany({ where });
  }

  createModel<T>(createAgentDto: T) {
    return this.prisma[this.model].create({
      data: createAgentDto,
    });
  }

  updateModel<T>(id: string, updateAgentDto: T) {
    return this.prisma[this.model].update({
      where: { id },
      data: updateAgentDto,
    });
  }
}
